//
//  AsmanLiteView.swift
//  vr
//
//  Created by 李旭峰 on 2020/7/20.
//

import UIKit
import RxSwift
import RxCocoa
import AudioToolbox
import AVFoundation
import SDWebImage

fileprivate var isNeedVibration:Bool = false
@objc protocol AsmanLiteViewDelegate {
    func router3DRoam()
    func rejectAnswer()
    func getTrtcAuthInfo()
    func notifyDesignerJoined()
    func canReceived(_ params:String)
    func answer(_ params:String)
}
class AsmanLiteView: BaseView {
    let dispose = DisposeBag()
    weak var delegate:AsmanLiteViewDelegate?
    private lazy var viewSchemeOutlineContiner: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hexStr: "#2B313D", alpha: 1.0)
        return view
    }()
    private lazy var schemeMainImage: UIImageView = {
        let imgView = UIImageView()
        imgView.contentMode = .scaleAspectFill
        return imgView
    }()
    private lazy var schemeName: UILabel = {
        let lb = UILabel()
        lb.textColor = UIColor.white
        lb.textAlignment = .left
        lb.font = FontAsset.PingFangSC_Regular.size(16.0)
        return lb
    }()
    private lazy var schemeHouseParams: UILabel = {
        let lb = UILabel()
        lb.textColor = UIColor.white
        lb.textAlignment = .left
        lb.font = FontAsset.PingFangSC_Regular.size(13.0)
        return lb
    }()
    private lazy var schemePrice: UILabel = {
        let lb = UILabel()
        lb.textColor = UIColor.white
        lb.textAlignment = .right
        lb.font = FontAsset.PingFangSC_Semibold.size(15.0)
        return lb
    }()
    
    private lazy var viewHeadImageContiner: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hexStr: "#1E232D", alpha: 1.0)
        return view
    }()
    private lazy var headImage: UIImageView = {
        let imgView = UIImageView()
        imgView.contentMode = .scaleAspectFill
        return imgView
    }()
    
    private lazy var name: UILabel = {
        let lb = UILabel()
        lb.textColor = UIColor.white
        lb.textAlignment = .center
        lb.font = FontAsset.PingFangSC_Regular.size(15.0)
        return lb
    }()
    private lazy var answerTag:UILabel = {
        let lb = UILabel()
        lb.textColor = UIColor.white
        lb.textAlignment = .center
        lb.text = "来客啦～接单啦～"
        lb.font = FontAsset.PingFangSC_Regular.size(28.0)
        return lb
    }()
    private lazy var viewCallActionContiner: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hexStr: "#1E232D", alpha: 1.0)
        return view
    }()
    private lazy var btnHangUp: UIButton = {
        let btn = UIButton(type: .custom)
        btn.titleEdgeInsets = UIEdgeInsets(top: 75, left: -70, bottom: 0, right: 0)
        btn.imageEdgeInsets = UIEdgeInsets(top: -30, left: 0, bottom: 0, right: 0)
        btn.setTitle("拒绝", for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.titleLabel?.font = FontAsset.PingFangSC_Regular.size(13.0)
        btn.setImage(UIImage(named: "Icon_Phone_Red_Fulfilled_Bottom"), for: .normal)
        btn.addTarget(self, action: #selector(onPressHangUp(_:)), for: .touchUpInside)
        return btn
    }()
    private lazy var btnAnswer: UIButton  = {
           let btn = UIButton(type: .custom)
           btn.bounds = CGRect(x: 0, y: 0, width: 70, height: 100)
           btn.titleEdgeInsets = UIEdgeInsets(top: 75, left: -70, bottom: 0, right: 0)
           btn.imageEdgeInsets = UIEdgeInsets(top: -30, left: 0, bottom: 0, right: 0)
           btn.setTitle("接听", for: .normal)
           btn.setTitleColor(UIColor.white, for: .normal)
           btn.titleLabel?.font = FontAsset.PingFangSC_Regular.size(13.0)
           btn.setImage(UIImage(named: "Icon_Phone_Green_Fulfilled_TopAndRight"), for: .normal)
           btn.addTarget(self, action: #selector(onPressAnswer(_:)), for: .touchUpInside)
           return btn
   }()
    
    let audioPlayer = AudioHelper()
    private var remain:Int = 0
    let schemeInfoDetailData:[String:Any]
    private lazy var displayLink:CADisplayLink = {
        let displayLink = CADisplayLink(target: self, selector: #selector(onHandleDisplayLinkAction))
        displayLink.preferredFramesPerSecond = 1
        displayLink.add(to: RunLoop.main, forMode: .common)
        displayLink.isPaused = true
        return displayLink
    }()
    
    let viewModel:AsmanLiteViewModel
    init(withInitialParams params:AsmanLiteViewModel.InitialParams,token:String,sdkAppId:String,userSig:String,schemeInfoDetailData:[String:Any]) {
        let viewModel = AsmanLiteViewModel(withInitialParams: params,token:token,sdkAppId:sdkAppId,userSig:userSig)
        self.viewModel = viewModel
        self.schemeInfoDetailData = schemeInfoDetailData
        super.init(frame: CGRect.zero)
        self.loadView()
        AsmanLiteManager.default.isWartEnterRoom = true
        NotificationCenter.default.addObserver(self, selector: #selector(onReceiveApplicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(onReceiveApplicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(onReceiveApplicationWillTerminate), name: UIApplication.willTerminateNotification, object: nil)
        self.viewDidLoad()
        self.viewWillAppear(false)
        self.viewDidAppear(false)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func loadView() {
        self.addSubview(self.viewSchemeOutlineContiner)
        self.addSubview(self.viewHeadImageContiner)
        self.addSubview(self.name)
        self.addSubview(self.answerTag)
        self.addSubview(viewCallActionContiner)
        
        self.viewSchemeOutlineContiner.snp.makeConstraints { (make) in
            make.leading.equalToSuperview().offset(30)
            make.trailing.equalToSuperview().offset(-30)
            make.top.equalToSuperview().offset(44)
            make.height.equalTo(94.0)
        }
        self.viewHeadImageContiner.snp.makeConstraints { (make) in
            make.top.equalTo(self.viewSchemeOutlineContiner.snp.bottom).offset(20)
            make.centerX.equalToSuperview()
            make.width.height.equalTo(240)
        }
        self.name.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(self.viewHeadImageContiner.snp.bottom).offset(20.0)
            make.leading.equalToSuperview().offset(20.0)
        }
        self.answerTag.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(self.name.snp.bottom).offset(20.0)
        }
        self.viewCallActionContiner.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(self.answerTag.snp.bottom).offset(0)
            make.bottom.equalToSuperview()
        }
        
        self.viewSchemeOutlineContiner.addSubview(self.schemeMainImage)
        self.viewSchemeOutlineContiner.addSubview(self.schemeName)
        self.viewSchemeOutlineContiner.addSubview(self.schemeHouseParams)
        self.viewSchemeOutlineContiner.addSubview(self.schemePrice)
        self.schemeMainImage.snp.makeConstraints { (make) in
            make.leading.equalToSuperview().offset(10)
            make.top.equalToSuperview().offset(10)
            make.bottom.equalToSuperview().offset(-10)
            make.width.equalTo(100)
        }
        self.schemeName.snp.makeConstraints { (make) in
            make.leading.equalTo(self.schemeMainImage.snp.trailing).offset(10.0)
            make.trailing.equalToSuperview().offset(-10.0)
            make.top.equalToSuperview().offset(10.0)
        }
        self.schemeHouseParams.snp.makeConstraints { (make) in
            make.leading.equalTo(self.schemeMainImage.snp.trailing).offset(10.0)
            make.trailing.equalToSuperview().offset(-10.0)
            make.centerY.equalToSuperview()
        }
        self.schemePrice.snp.makeConstraints { (make) in
            make.leading.equalTo(self.schemeMainImage.snp.trailing).offset(10.0)
            make.trailing.equalToSuperview().offset(-10.0)
            make.bottom.equalToSuperview().offset(-10)
        }
        
        self.viewHeadImageContiner.addSubview(self.headImage)
        self.headImage.snp.makeConstraints { (make) in
            make.width.height.equalTo(100)
            make.center.equalToSuperview()
        }
        
        self.viewCallActionContiner.addSubview(self.btnHangUp)
        self.viewCallActionContiner.addSubview(self.btnAnswer)
        self.btnHangUp.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.centerX.equalToSuperview().multipliedBy(0.5)
            make.width.equalTo(70)
            make.height.equalTo(100)
        }
        self.btnAnswer.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.centerX.equalToSuperview().multipliedBy(1.5)
            make.width.equalTo(70)
            make.height.equalTo(100)
        }
    }

    func viewDidLoad() {
        self.backgroundColor = UIColor(hexStr: "#1E232D", alpha: 1.0)
        self.viewHeadImageContiner.backgroundColor = UIColor(hexStr: "#1E232D", alpha: 1.0)
        self.viewCallActionContiner.backgroundColor = UIColor(hexStr: "#1E232D", alpha: 1.0)
        
        
        self.name.text = self.viewModel.name
        let headUrl = URL(string: self.viewModel.headUrl.analyseCnString()) ?? URL(string: "https://img.asman.com.cn/assets/1575555291735_75384.png")
        self.headImage.sd_setImage(with: headUrl, placeholderImage: nil, options: []) {[weak self] (image, error, cacheType, url) in
            guard let `self` = self else { return }
            self.headImage.image = image
        }
        
        let scheme = Scheme(self.schemeInfoDetailData)
        self.viewSchemeOutlineContiner.isHidden = false
        self.schemeMainImage.sd_setImage(with: URL(string: scheme.schemeImage.analyseCnString().oss_level01()), placeholderImage: nil, options: []) {[weak self] (image, error, cacheType, url) in
            guard let `self` = self else { return }
            self.schemeMainImage.image = image
        }
        var schemeNameText:String = scheme.buildingName
        if scheme.styleName.count > 0 {
            if schemeNameText.count > 0 {
                schemeNameText = schemeNameText + "·"
            }
            schemeNameText = schemeNameText + scheme.styleName
        }
        self.schemeName.text = schemeNameText
        
        let buildArea = scheme.buildingArea
        var schemeHouseParamsText:String = ""
        if buildArea > 0 {
            schemeHouseParamsText = "\(buildArea)m²"
        }
        schemeHouseParamsText = (scheme.houseParams.houseParams([.kBedroomNum,.kLivingRoomNum]) )
        self.schemeHouseParams.text = schemeHouseParamsText
        var schemePriceText = ""
        if scheme.price > 0 {
            schemePriceText = scheme.price.toCNPrice()
        }
        self.schemePrice.text = schemePriceText
        
        self.remain = 0
        self.displayLink.isPaused = false
        isNeedVibration = true
        self.systemVibration()
        let filePath = Bundle.main.path(forResource: "rtcPushSound_02", ofType: "caf") ?? ""
        self.audioPlayer.playMusic(filePath: filePath)
    }
    func viewWillAppear(_ animated: Bool) {
        if self.tempLayer != nil {
            self.tempLayer?.removeAllAnimations()
            self.tempLayer?.removeFromSuperlayer()
            self.tempLayer = nil
        }
        self.tempLayer = self.makeRadarAnimation(withShowRect: self.headImage.frame, isRound: true)
        self.viewHeadImageContiner.layer.insertSublayer(self.tempLayer!, below: self.headImage.layer)
        self.startAnimate()
    }
    func viewDidAppear(_ animated: Bool) {
        self.startAnimate()
    }
    func viewDidDisappear(_ animated: Bool) {
        clearData()
    }
    private func clearData(){
        AsmanLiteManager.default.isWartEnterRoom = false
        NotificationCenter.default.removeObserver(self)
        isNeedVibration = false
        self.stopAnimate()
        self.audioPlayer.stopCurrentMusic()
    }
    deinit {
    }
    
    @objc private func onPressHangUp(_ sender: UIButton) {
        var params:[String:Any] = [:]
        params["rendering_id"] = self.viewModel.schemeId
        params["user_id"] = self.viewModel.userId
//        MobClick.TapEvent.insertEvent(attributes: params, forKey: .kVoiceRefuse)
        self.viewModel.reject {[weak self] (_, _) in
            guard let `self` = self else { return }
            isNeedVibration = false
            self.stopAnimate()
            self.deinitDisplayLink()
            AsmanLiteManager.default.deinitRtcRoom()
            self.delegate?.rejectAnswer()
            self.viewDidDisappear(false)
            //TODO: 退出页面
//            UIApplication.shared.navigationController?.popViewController(animated: true)
        }
    }
    @objc private func onPressAnswer(_ sender: UIButton) {
        self.deinitDisplayLink()
        isNeedVibration = false
        
        var params:[String:Any] = [:]
        params["rendering_id"] = self.viewModel.schemeId
        params["user_id"] = self.viewModel.userId
//        MobClick.TapEvent.insertEvent(attributes: params, forKey: .kVoiceListen)
        self.viewModel.rtcAnswer(callBack: nil)
        let answerSuccessAction = "answerSuccess"
        let answerFailAction = "answerFail"
        let answerErrorAction = "answerError"
        self.delegate?.answer("\(answerSuccessAction),\(answerFailAction),\(answerErrorAction)")
        /*
        let userId = self.viewModel.userId
        let roomId = self.viewModel.roomId
        let sdkAppId = self.viewModel.sdkAppId.decimal.uint32Value
        let userSig = self.viewModel.userSig
        AsmanLiteManager.default.enterRoom(sdkAppId: sdkAppId, userSig: userSig, userId: userId, roomId: roomId) { (success, error, code) in
           if !success {
                            DispatchQueue.main.async {
            //                        CXMBShow.showMessage("当前通话已断开")
                                AsmanLiteManager.default.deinitRtcRoom()
                                self.delegate?.rejectAnswer()
                                self.viewDidDisappear(false)
                            }
                            return
                        }

                        DispatchQueue.main.async {
                            self.delegate?.router3DRoam()
                            self.viewDidDisappear(false)
                        }
        }*/
    }
    /// 响应程序挂起
    @objc private func onReceiveApplicationWillResignActive(){
        self.tempLayer?.removeAllAnimations()
        self.tempLayer?.removeFromSuperlayer()
        self.tempLayer = nil
    }
    /// 响应重新进入程序
    @objc private func onReceiveApplicationDidBecomeActive(){
        if self.tempLayer != nil {
            self.tempLayer?.removeAllAnimations()
            self.tempLayer?.removeFromSuperlayer()
            self.tempLayer = nil
        }
        self.tempLayer = self.makeRadarAnimation(withShowRect: self.headImage.frame, isRound: true)
        self.viewHeadImageContiner.layer.insertSublayer(self.tempLayer!, below: self.headImage.layer)
        self.startAnimate()
    }
    /// 响应程序被杀死
    @objc private func onReceiveApplicationWillTerminate(){
        self.viewModel.reject(withCallBack: nil)
    }
    func deinitDisplayLink(){
        self.displayLink.isPaused = true
        self.displayLink.invalidate()
    }
    @objc private func onHandleDisplayLinkAction(){
        if self.remain % 5 == 0 {
            AsmanLiteManager.default.syncLoadRtcCallStatus(roomId: String(self.viewModel.roomId)) {[weak self] (success, error) in
                guard let `self` = self else { return }
                if success { return }
                DispatchQueue.main.async {
                    isNeedVibration = false
                    self.stopAnimate()
                    self.deinitDisplayLink()
                    AsmanLiteManager.default.deinitRtcRoom()
                }
            }
        }
        self.remain += 1
    }
    
    private func startAnimate(){
        animationLayer.add(animationGroup, forKey: radarAnimation)
    }
    private func stopAnimate(){
        animationLayer.removeAnimation(forKey: radarAnimation)
    }
    private var tempLayer:CALayer?
    private let radarAnimation = "radarAnimation"   //对象1
    private lazy var animationLayer: CAShapeLayer = {
        // 1. 一个动态波
        let shapeLayer = CAShapeLayer()
        shapeLayer.fillColor = UIColor(hexStr: "#1E232D", alpha: 1.0).cgColor    //波纹颜色
        shapeLayer.lineWidth = 1.0
        shapeLayer.strokeColor = UIColor(hexStr: "#FFFFFF", alpha: 0.6).cgColor
        shapeLayer.opacity = 0.0    // 默认初始颜色透明度
        return shapeLayer
    }()
    private lazy var animationGroup: CAAnimationGroup = {
        
        // 2. 创建动画组 from -> to 透明比例过渡
        let opacityAnimation = CABasicAnimation(keyPath: "opacity")
        opacityAnimation.fromValue = NSNumber(floatLiteral: 1.0)  // 开始透明度
        opacityAnimation.toValue = NSNumber(floatLiteral: 0)      // 结束时透明底
        
        // 3. 波纹动画 起始大小
        let scaleAnimation = CABasicAnimation(keyPath: "transform")
        scaleAnimation.fromValue = NSValue.init(caTransform3D: CATransform3DScale(CATransform3DIdentity, 1.0, 1.0, 0))      // 缩放起始大小
        scaleAnimation.toValue = NSValue.init(caTransform3D: CATransform3DScale(CATransform3DIdentity, 2.5, 2.5, 0))      // 缩放结束大小
        
        // 4. 定义波的运行时间
        let animationGroup = CAAnimationGroup()
        animationGroup.animations = [opacityAnimation, scaleAnimation]  //引用opacityAnimation 和 scaleAnimation
        animationGroup.duration = 3.0       // 动画执行时间
        animationGroup.repeatCount = HUGE   // 最大重复
        animationGroup.autoreverses = false
        return animationGroup
    }()
    private func makeRadarAnimation(withShowRect showRect:CGRect, isRound:Bool) -> CALayer {
        self.animationLayer.frame = showRect
        self.animationLayer.path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: showRect.width, height: showRect.height)).cgPath
        self.animationLayer.add(animationGroup, forKey: radarAnimation)  //全局对象1 radarAnimation
        
        // 5. 需要重复的动态波，数量，缩放起始点 <=> 创建副本
        let replicator = CAReplicatorLayer()
        replicator.frame = self.animationLayer.bounds
        replicator.instanceCount = 7
        replicator.instanceDelay = 0.5
        replicator.addSublayer(self.animationLayer)
        
        return replicator
    }
    
    private func systemVibration() {
        //建立的SystemSoundID对象
        let soundID = SystemSoundID(kSystemSoundID_Vibrate)//kSystemSoundID_Vibrate
        AudioServicesAddSystemSoundCompletion(soundID,
                                              nil,
                                              nil,
                                              { (sound, _) in
                                                if !isNeedVibration { return }
                                                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
                                                    if !isNeedVibration { return }
                                                    AudioServicesPlaySystemSound(sound)
                                                }
                                              },
                                              nil)
        //振动
        AudioServicesPlaySystemSound(soundID)
    }
}
typealias AsmanLiteAnswerCallBack = ()->Void
extension AsmanLiteView {
    func answerSuccess(_ callBack:@escaping AsmanLiteAnswerCallBack){
        self.delegate?.router3DRoam()
        AsmanLiteManager.default.enterRoom(sdkAppId: self.viewModel.sdkAppId.decimal.uint32Value, userSig: self.viewModel.userSig, userId: self.viewModel.userId, roomId: self.viewModel.roomId, callBack: nil)
        self.viewDidDisappear(false)
    }
    func answerFail(_ callBack:@escaping AsmanLiteAnswerCallBack){
        AsmanLiteManager.default.deinitRtcRoom()
//        self.delegate?.rejectAnswer()
        self.viewDidDisappear(false)
    }
    func answerError(_ callBack:@escaping AsmanLiteAnswerCallBack){
        AsmanLiteManager.default.deinitRtcRoom()
//        self.delegate?.rejectAnswer()
        self.viewDidDisappear(false)
    }
}
